﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Build.Framework;

namespace ZealandIT.MsBuildTasks.IO
{
    /// <summary>
    /// MSBuild task that removes directory(ies) and uses impersonation - if username/pw specified.
    /// This allows the operation to work over UNC / network paths.
    /// </summary>
    public class RmDir : BaseImpersonationTask
    {
        private ITaskItem[] _directories;

        /// <summary>
        /// Directories to be removed.
        /// </summary>
        [Required]
        public ITaskItem[] Directories
        {
            get { return _directories; }
            set { _directories = value; }
        }

        /// <summary>
        /// Main method that performs the deletion/removal of directories. This method is called from its
        /// abstract base class' <see cref="BaseImpersonationTask.Execute"/> method.
        /// </summary>
        /// <returns>True if successful, else false.</returns>
        protected override bool ExecuteInternal()
        {
            foreach (ITaskItem item in _directories)
            {
                try
                {
                    if (item.ItemSpec.Length > 0 && Directory.Exists(item.ItemSpec))
                    {
                        Log.LogMessage(string.Format("Removing directory \"{0}\"...", item.ItemSpec));
                        Directory.Delete(item.ItemSpec, true);
                        Log.LogMessage("..done.");
                    }
                }
                catch (Exception ex)
                {
                    Log.LogMessage("..FAILED.");
                    Log.LogErrorFromException(ex);
                    return false;
                }
            }
            return true;
        }
    }
}
